package com.adou.Controller;

import com.adou.common.controller.BaseController;
import com.adou.common.dto.FlowTaskOutDto;
import com.adou.common.model.FlowTask;
import com.adou.common.util.Const;
import com.adou.common.util.StringUtil;
import com.adou.service.FlowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("flowTask")
@Scope(value = "prototype")
public class FlowTaskController extends BaseController {

    @Autowired
    private FlowTaskService flowTaskService;

    /**
     * 流程环节分页
     * @param pageNum
     * @param pageSize
     * @param o
     * @param find 模糊查询内容：流程名称、环节名称、环节类型
     * @return
     */
    @GetMapping("pageList")
    private Map<String, Object> pageList(int pageNum, int pageSize, FlowTask o ,String find){
        pageNum = pageNum <= 0 ? this.pageNum : pageNum;
        pageSize = pageSize <= 0 ? this.pageSize : pageSize;
        if(o.getIfmid()==null || o.getIfmid()==0){
            error(101,"流程主键为空");
            return resultMap;
        }
        o.setCtaskname(find);
        try {
            Map<String, Object> map = flowTaskService.findByPage(pageNum,pageSize,o);
            if ((long) map.get("totalcount") > 0) {
                List<FlowTask> flowTaskList=(List<FlowTask>)map.get("list");
                List<FlowTaskOutDto> flowTaskOutDtoList = flowTaskList.stream().map(FlowTaskOutDto::new).collect(Collectors.toList());
                map.put("list", flowTaskOutDtoList);
                resultMap.put("data", map);
                resultMap.put("msg", Const.DATA_SUCCEED);
            } else {
                error(101, "数据为空");
            }
        }
        catch (Exception e){
            resultMap.put("result", Const.DATA_ERROR_112);
            resultMap.put("msg", Const.DATA_FAIL);
            logger.error(e.toString());
        }
        return resultMap;
    }

    /**
     * 添加流程环节
     * @param flowTask
     * @return
     */
    @PostMapping("insert")
    private  Map<String, Object> insert(FlowTask flowTask){
        if(StringUtil.isBlank(flowTask.getCtaskname())){
            error(201,"节点名称为空");
            return resultMap;
        }
        if(StringUtil.isBlank(flowTask.getCtasktype())){
            error(202,"节点类型为空");
            return resultMap;
        }
        if(StringUtil.isBlank(flowTask.getIfmid())){
            error(203,"流程主键为空");
            return resultMap;
        }
        if(flowTask.getbIsDepHandle() || flowTask.getbIsAreaHandle()){
            if(StringUtil.isBlank(flowTask.getCconductusers())){
                error(204,"设置按区域或按部门办理，请选择办理人");
                return resultMap;
            }
            if(StringUtil.isBlank(flowTask.getCconductids()) || !StringUtil.isInteger(flowTask.getCconductids().replaceAll(",",""))){
                error(205,"办理人ids为空或格式错误");
                return resultMap;
            }
        }
        try {
            int res = flowTaskService.insert(flowTask);
            if (res==0){
                resultMap.put("result",Const.ADD_ERROR_201);
                resultMap.put("msg",Const.SAVE_FAIL);
            }else {
                resultMap.put("msg", Const.SAVE_SUCCEED);
                resultMap.put("data",res);
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            resultMap.put("result", Const.ADD_ERROR_202);
            resultMap.put("msg", Const.SAVE_FAIL);
        }
        return resultMap;
    }

    /**
     * 修改流程环节
     * @param flowTask
     * @return
     */
    @PostMapping("update")
    private  Map<String, Object> update(FlowTask flowTask){
        if(StringUtil.isBlank(flowTask.getId())){
            error(213,"id为空");
            return resultMap;
        }
        if(StringUtil.isBlank(flowTask.getCtaskname())){
            error(214,"节点名称为空");
            return resultMap;
        }
        if(StringUtil.isBlank(flowTask.getCtasktype())){
            error(215,"节点类型为空");
            return resultMap;
        }
        if(StringUtil.isBlank(flowTask.getIfmid())){
            error(216,"流程主键为空");
            return resultMap;
        }
        if(flowTask.getbIsDepHandle() || flowTask.getbIsAreaHandle()){
            if(StringUtil.isBlank(flowTask.getCconductusers())){
                error(217,"设置按区域或按部门办理，请选择办理人");
                return resultMap;
            }
            if(StringUtil.isBlank(flowTask.getCconductids()) || !StringUtil.isInteger(flowTask.getCconductids().replaceAll(",",""))){
                error(218,"办理人ids为空或格式错误");
                return resultMap;
            }
        }
        try {
            int res = flowTaskService.update(flowTask);
            if (res==0){
                resultMap.put("result",Const.UPDATE_ERROR_211);
                resultMap.put("msg",Const.UPDATE_FAIL);
            }else {
                resultMap.put("msg", Const.UPDATE_SUCCEED);
                resultMap.put("data",res);
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            resultMap.put("result", Const.UPDATE_ERROR_212);
            resultMap.put("msg", Const.UPDATE_FAIL);
        }
        return resultMap;
    }

    /**
     * 根据主键修改状态
     * @param o 必传id,选传 bIsDepHandle，bIsAreaHandle，bIsTracing，
     *          bIsReturn，bIsPrint，bIsEdit，bIsNotes（7个必选一个）
     * @return
     */
    @PostMapping("updateStatusById")
    private Map<String, Object> updateStatusById(FlowTask o){
        if (o.getId()==0){
            error(201,"id错误");
            return resultMap;
        }
        FlowTask flowTask = new FlowTask();
        flowTask.setId(o.getId());
        List<FlowTask> list = flowTaskService.find(flowTask);
        if(list==null || list.size()==0){
            error(203,"流程节点不存在");
            return resultMap;
        }
        if(o.getbIsAreaHandle()!=null){
            if(o.getbIsAreaHandle()){
                if(StringUtil.isNotBlank(list.get(0).getCconductusers())){
                    flowTask.setbIsAreaHandle(o.getbIsAreaHandle());
                }else {
                    error(202,"设置按区域办理，办理人不存在，请使用修改方法");
                    return resultMap;
                }
            }
            else {
                flowTask.setbIsAreaHandle(o.getbIsAreaHandle());
            }
        }
        if(o.getbIsDepHandle()!=null){
            if(o.getbIsDepHandle()){
                if(StringUtil.isNotBlank(list.get(0).getCconductusers())){
                    flowTask.setbIsDepHandle(o.getbIsDepHandle());
                }else {
                    error(202,"设置按部门办理，办理人不存在，请使用修改方法");
                    return resultMap;
                }
            }
            else {
                flowTask.setbIsDepHandle(o.getbIsDepHandle());
            }
        }
        if(o.getbIsTracing()!=null){
            flowTask.setbIsTracing(o.getbIsTracing());
        }
        if(o.getbIsReturn()!=null){
            flowTask.setbIsReturn(o.getbIsReturn());
        }
        if(o.getbIsPrint()!=null){
            flowTask.setbIsPrint(o.getbIsPrint());
        }
        if(o.getbIsEdit()!=null){
            flowTask.setbIsEdit(o.getbIsEdit());
        }
        if(o.getbIsNotes()!=null){
            flowTask.setbIsNotes(o.getbIsNotes());
        }
        if(o.getbIsTel()!=null){
            flowTask.setbIsTel(o.getbIsTel());
        }
        try {
            int res = flowTaskService.update(flowTask);
            if (res==0){
                resultMap.put("result",Const.UPDATE_ERROR_211);
                resultMap.put("msg","操作失败");
            }else {
                resultMap.put("msg", Const.UPDATE_SUCCEED);
                resultMap.put("data","操作成功");
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            resultMap.put("result", Const.UPDATE_ERROR_212);
            resultMap.put("msg", "操作失败");
        }
        return resultMap;
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("delete")
    private  Map<String, Object> delete(String ids){
        if(!StringUtil.isInteger(ids.replaceAll(",",""))){
            error(303,"ids格式错误");
            return resultMap;
        }
        try {
            List<FlowTask> list = new ArrayList<>();
            for (String id: ids.split(",")) {
                FlowTask flowTask = new FlowTask();
                flowTask.setId(Long.parseLong(id));
                list.add(flowTask);
            }
            int res = flowTaskService.deleteBatch(list);
            if (res==0){
                resultMap.put("result",Const.DEL_ERROR_301);
                resultMap.put("msg",Const.DEL_FAIL);
            }
            else if(res==-1){
                error(303,"流程运行主表已包含数据，无法删除");
            }
            else {
                resultMap.put("msg", Const.DEL_SUCCEED);
                resultMap.put("data",res);
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DEL_ERROR_302);
            resultMap.put("msg", Const.DEL_FAIL);
        }
        return resultMap;
    }

    /**
     * 根据主键查询节点详细信息
     * @param id
     * @return
     */
    @GetMapping("find")
    private  Map<String, Object> find(Long id){
        if(id == null || id == 0){
            error(103,"id未传");
            return resultMap;
        }
        try {
            FlowTask flowTask = new FlowTask();
            flowTask.setId(id);
            List<FlowTask> list = flowTaskService.find(flowTask);
            if(list.size()==1){
                resultMap.put("data",list.get(0));
            }
            else {
                error(101,"未查询到相关数据");
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            error(102, "查询数据出现错误");
        }
        return resultMap;
    }

    /**
     * 查询节点（去除办结节点）
     * @param id 流程主键
     * @return
     */
    @GetMapping("queryNodes")
    public Map<String, Object> queryNodes(String id){
        if(StringUtil.isBlank(id)){
            error(101, "主键为空");
            return resultMap;
        }
        try {
            List<FlowTask> flowTaskList = flowTaskService.queryNodes(id);
            if(flowTaskList.size() == 0){
                error(103, "数据为空");
                return resultMap;
            }
            resultMap.put("data", flowTaskList);
        } catch (Exception e){
            logger.error(e.toString(), e);
            error(102, "查询数据出现错误");
        }
        return resultMap;
    }

}
